﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace Nonocast.Http.Misc {
	public class HttpHelper {
		public static string HttpPost(string url, object obj) {
			string content = string.Empty;

			WebRequest request = WebRequest.Create(url);
			var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
			byte[] data = Encoding.UTF8.GetBytes(json);
			request.Method = "POST";
			request.ContentType = "application/json";
			request.ContentLength = data.Length;
			Stream postStream = request.GetRequestStream();
			postStream.Write(data, 0, data.Length);
			postStream.Close();

			WebResponse response = request.GetResponse();
			Stream stream = response.GetResponseStream();
			using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
				content = reader.ReadToEnd();
			}
			stream.Close();
			response.Close();

			return content;
		}

		public static string HttpGet(string url) {
			string content = string.Empty;
			WebRequest request = WebRequest.Create(url);
			WebResponse response = request.GetResponse();
			Stream stream = response.GetResponseStream();
			using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
				content = reader.ReadToEnd();
			}
			stream.Close();
			response.Close();
			return content;
		}
	}
}
